﻿@inject IUserService UserService
@inject IMessageService MessageService

<Collapse>
	<Panel Header="添加" Key="0">
		<Select TItem="SimpleUser"
				TItemValue="Guid"
				DataSource="@_usersNotInCourse"
				LabelName="@nameof(SimpleUser.Name)"
				ValueName="@nameof(SimpleUser.Id)"
				EnableSearch
				Mode="multiple"
		@bind-Values="@_selectedUsersId">
		</Select>
		<Button OnClick="AddUserToCourse">添加上述用户</Button>
	</Panel>
	<Panel Header="删除" Key="1">
		@if (_usersInCourse != null && _usersInCourse.Count >= 0)
		{
			<AntList DataSource="@_usersInCourse" ItemLayout="ListItemLayout.Horizontal">
				<ChildContent>
					<ListItem>
						<p>@context.Name <a @onclick="()=>RemoveUserFromCourse(context.Id)">删除</a></p>
					</ListItem>
				</ChildContent>
			</AntList>
		}
		else
		{
			<Empty/>
		}
	</Panel>
</Collapse>
@code {

	public class SimpleUser
	{
		public Guid Id { get; set; }
		public string Name { get; set; }
	}

	[Parameter]
	public List<UserWithCourse> UserWithCourses { get; set; }
	[Parameter]
	public Guid CourseId { get; set; }

	List<SimpleUser> _usersInCourse = new();
	List<SimpleUser> _usersNotInCourse = new();
	
	protected override async Task OnParametersSetAsync()
	{
		UpdateUserCourse(UserWithCourses);
	}

	// 划分用户是否在课程中，更新页面状态
	private void UpdateUserCourse(List<UserWithCourse> userWithCourses)
	{
		_usersInCourse.Clear();
		_usersNotInCourse.Clear();
		foreach (var user in userWithCourses)
		{
			if (user.IsInCourse)
			{
				_usersInCourse.Add(new() { Id = user.UserId, Name = user.UserName });
			}
			else
			{
				_usersNotInCourse.Add(new() { Id = user.UserId, Name = user.UserName });
			}
			StateHasChanged();
		}
	}

	// 从课程中移出所选用户
	public async void RemoveUserFromCourse(Guid userId)
	{
		// 弹窗判断下
		var response = await UserService.RemoveUserFromCourse(CourseId, new() { userId });
		if (response.Success)
		{
			UpdateUserCourse(response.Data??new());
			_selectedUsersId = new List<Guid>();
			await MessageService.Success("成功删除用户!");
		}
	}

	// 增加所选用户到课程中
	private IEnumerable<Guid> _selectedUsersId { get; set; } = new List<Guid>();
	private async void AddUserToCourse()
	{
		if (_selectedUsersId.Any())
		{
			var response = await UserService.AddUserToCourse(CourseId, _selectedUsersId.ToList());
			if (response.Success)
			{
				UpdateUserCourse(response.Data??new());
				_selectedUsersId = new List<Guid>();
				await MessageService.Success("成功添加用户!");
			}
		}
	}

}
